<?php
$address = dirname(dirname(__FILE__)).'/PHPExcel';
require_once $address.'/PHPExcel.class.php';
require_once $address.'/PHPExcel/Writer/Excel2007.php';
require_once $address.'/PHPExcel/Writer/Excel5.php';
require_once $address.'/PHPExcel/IOFactory.php';
require_once $address.'/PHPExcel/Worksheet.php';

/****************************
*向excel文档写入数据。
*/

class excelU {
  var $startrow = 0;
  
  /*function __construct($fn) {
    $this->tpl = PHPExcel_IOFactory::load($fn);
    $this->target = clone $this->tpl;
  }*/
  
  function Initialization($fn) {
    $this->tpl = PHPExcel_IOFactory::load($fn);
    $this->target = clone $this->tpl;
  }
  
  function add_data($ar) {
    $ar = array_values($ar);
//    if(!isset($this->target)) $this->target = clone $this->tpl;
    $sheet = $this->tpl->getActiveSheet();
    $i = 0;
    foreach($sheet->getRowDimensions() as $y=>$row) {
      foreach($sheet->getColumnDimensions($row) as $x=>$col) {
        $txt = trim($sheet->getCell($x.$y)->getValue());
        if($txt && $txt{0} == '#') $txt = isset($ar[$i]) ? $ar[$i++] : '';
        $h = $y + $this->startrow;
        $this->target->getActiveSheet()->getCell("$x$h")->setValue($txt);
        $this->target->getActiveSheet()->duplicateStyle($sheet->getStyle("$x$y"), "$x$h");
      }
    }
    foreach($sheet->getMergeCells() as $merge) {
      $merge = preg_replace('/\d+/e',"$0+$this->startrow", $merge);
      $this->target->getActiveSheet()->mergeCells($merge);
    }
    $this->startrow += $sheet->getHighestRow() + 3;//多加3行便于裁剪
  }
  
  function output0($fn) {
    $t = PHPExcel_IOFactory::createWriter($this->target, 'Excel5');
    $t->save($fn);
  }

  function output1($fn) {
  	ob_end_clean();//清除缓冲区,避免乱码
  	header('Content-Type: application/vnd.ms-excel'); 
			$excel = 'Excel5';
	header("Content-Disposition: attachment; filename=\"$fn\"");
	 	header('Cache-Control: max-age=0');		
    $t = PHPExcel_IOFactory::createWriter($this->target, 'Excel5');
//echo '11111b';    //exit;
    //$t->save($fn);
    $t->save('php://output');
  }

  function output2($fn,$phpexcel) {
  	ob_end_clean();//清除缓冲区,避免乱码
  	//导出属性设置
     /*$date = str_replace("/","_",$date);
     $outputFileName = "kaoqing_".$date.".xlsx";*/
     //$outputFileName = "kaoqing_".time().".xlsx";
     $outputFileName = $fn;
     //require_once("Classes/PHPExcel/Writer/Excel2007.php"); 
     //$phpexcel = $this->target;
     //$objWriter = new PHPExcel_Writer_Excel2007($phpexcel);
     $objWriter = new PHPExcel_Writer_Excel2007($phpexcel);
     header("Content-Type: application/force-download");
     header("Content-Type: application/octet-stream");
     header("Content-Type: application/download");
     header('Content-Disposition:inline;filename="'.$outputFileName.'"');
     header("Content-Transfer-Encoding: binary");
     header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Pragma: no-cache");
     $objWriter->save('php://output');
  }

  function output($fn,$phpexcel) {
  	ob_end_clean();//清除缓冲区,避免乱码
  	header('Content-Type: application/vnd.ms-excel'); 
	header("Content-Disposition: attachment; filename=\"$fn\"");
	header('Cache-Control: max-age=0');		
    $t = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
    $t->save('php://output');
  }

	/*Excel样式置
	*$obj      Excel对象
	*$column   列
	*$setSize  字体大小
	*$isBold   是否加粗
	*$background  设置背景色
	*$textColor  字体颜色
	*$Underline  下划线
	*/
	public function styleSet($obj,$column,$typeface='宋体',$setSize=10,$isBold=false,$background='',$textColor='',$Underline=''){
		$objStyleA  = $obj->getStyle("$column");       
		$objStyleA->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objStyleA->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);   
		$objFontA = $objStyleA->getFont();       
		$objFontA->setName($typeface);       
		$objFontA->setSize($setSize);    
		if($isBold){
			$objFontA->setBold(true); 
		}
		if($background){
			$objFontA->background($background); 
		}
		if($textColor){
			$objFontA->textColor($textColor); 
		}
		if($Underline){
			$objFontA->setUnderline($Underline); 
		}
	}

	/*php将文件夹打包成zip文件*/
		/*  说明: 将多个文件压缩成一个zip文件的函数 
	*   @param   $files  数组类型 
	*   @param   destination  目标文件的路径 
	*   @param   $overwrite   是否为覆盖与目标文件相同的文件 
	*/
	public function create_zip($files = array(),$destination = '',$overwrite = false){  
		//如果zip文件已经存在并且设置为不重写返回false  
		if(file_exists($destination) && !$overwrite) { return false; }  
		$valid_files = array();  
		//获取到真实有效的文件名  
		if(is_array($files)) {  
			foreach($files as $file) {  
				if(file_exists($file)) {  
					$valid_files[] = $file;  
				}  
			}  
		}  
		//如果存在真实有效的文件  
		if(count($valid_files)) {  
			$zip = new ZipArchive();  
			//打开文件 如果文件已经存在则覆盖，如果没有则创建  
			if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {  return false;  }  
			//向压缩文件中添加文件  
			foreach($valid_files as $file) {  
				$fileName = basename($file);//取出文件名字
				if(!strstr($file,'evaluationDetails')){
					$zip->addFile($file,$fileName);
				}  
			}  
			//关闭文件  
			$zip->close();  
			//检测文件是否存在  
			return file_exists($destination);  
		}else{ 
			return false;  
		}  
	} 

	//PHP遍历某个目录下的所有文件和子文件夹的实现代码
	public  function read_all_dir ($dir) {
		$result = array();
		$handle = opendir($dir);
		if ( $handle )
		{
			while ( ( $file = readdir ( $handle ) ) !== false )
			{
				if ( $file != '.' && $file != '..')
				{
					$cur_path = $dir . DIRECTORY_SEPARATOR . $file;
					if ( is_dir ( $cur_path ) )
					{
						$result['dir'][$cur_path] = $this->read_all_dir ( $cur_path );
					}
					else
					{
						$result['file'][] = $cur_path;
					}
				}
			}
			closedir($handle);
		}
		return $result;
	}
	
	/*
	*获取目录，主机信息
	*/
	public function getRoom(){
		//请求类型
		$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';  
		//当前项目所在目录
		$projectDir = substr($_SERVER['SCRIPT_NAME'],0,strpos($_SERVER['SCRIPT_NAME'],'/',2)+1);
		if($_SERVER['HTTP_HOST'] == 'zdjs.sefsoft.com'){
			$host = $http_type.$_SERVER['HTTP_HOST'].'/';
			$dir  = '/';
		}else{
			$host =  $http_type.$_SERVER['HTTP_HOST'].$projectDir;
			$dir  = $projectDir;
		}
		
		return array('dir'=>$dir,'host'=>$host);
	}	
	
}
